<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getDepartmentList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="insertDialogVisible = true">新增部门</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ") }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openInsertDialog(scope.row)">新增</el-button>
        <el-button type="primary" link :icon="Delete" @click="updateDepartmentStatus(scope.row, -1)">禁用</el-button>
      </template>
    </ProTable>
    <el-dialog width="40%" v-model="insertDialogVisible" title="新增部门">
      <el-form ref="insertFormRef" :model="insertParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="上级部门" prop="parentDepartmentId">
          <el-tree-select v-model="insertParam.parentDepartmentId" :data="dptTree" check-strictly :default-expand-all="true" />
        </el-form-item>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="departmentName">
              <el-input v-model="insertParam.departmentName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号码" prop="orderNum">
              <el-input-number v-model="insertParam.orderNum"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="部门编码">
              <el-input v-model="insertParam.departmentNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="insertParam.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="insertParam.telephone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="insertParam.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="insertParam.departmentDesc" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="insertDepartment(insertFormRef)">新增</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog width="40%" v-model="updateDialogVisible" title="修改部门信息">
      <el-form ref="updateFormRef" :model="updateParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="上级部门" prop="parentDepartmentId">
          <el-tree-select v-model="updateParam.parentDepartmentId" :data="dptTree" check-strictly :default-expand-all="true" />
        </el-form-item>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="departmentName">
              <el-input v-model="updateParam.departmentName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号码" prop="orderNum">
              <el-input-number v-model="updateParam.orderNum"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="部门编码">
              <el-input v-model="updateParam.departmentNumber" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="updateParam.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="updateParam.telephone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="updateParam.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="updateParam.departmentDesc" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateDepartment(updateFormRef)">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="departmentManage">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import {
  getDepartmentList,
  getDepartmentTree,
  createDepartment,
  editDepartmentInfo,
  editDepartmentStatus
} from "@/api/modules/auth/department";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, ElementPlus } from "@element-plus/icons-vue";
import {
  CreateDepartmentParam,
  DepartmentTreeResult,
  EditDepartmentInfoParam,
  GetDepartmentListParam
} from "@/api/interface/auth/department";
import { statusEnum, statusFieldNames } from "@/enums/httpEnum";
import { SelectTreeOptionResult } from "@/api/interface";

// ProTable 实例
const proTable = ref<ProTableInstance>();

const insertFormRef = ref<FormInstance>();

const updateFormRef = ref<FormInstance>();

const insertDialogVisible = ref(false);

const updateDialogVisible = ref(false);

let dptTree = reactive<SelectTreeOptionResult[]>([]);

/** 新增参数 */
const insertParam = reactive<CreateDepartmentParam>({
  departmentName: "",
  departmentNumber: "",
  parentDepartmentId: "",
  orderNum: 0,
  telephone: undefined,
  email: undefined,
  status: 0
});

/** 修改参数 */
const updateParam = reactive<EditDepartmentInfoParam>({
  departmentId: "",
  departmentName: "",
  status: 1,
  parentDepartmentId: "",
  departmentDesc: "",
  departmentNumber: "",
  orderNum: 0
});

const ruleForm = reactive<FormRules>({
  departmentName: [{ required: true, message: "请输入部门名称", trigger: "change" }],
  parentDepartmentId: [{ required: true, message: "请选择父级部门Id", trigger: "change" }],
  orderNum: [{ required: true, message: "请输入排序号码", trigger: "change" }]
});

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<GetDepartmentListParam>({});

// 表格配置项
const columns = reactive<ColumnProps<DepartmentTreeResult>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "departmentName",
    label: "部门名称",
    search: { el: "input", tooltip: "请输入部门名称" }
  },
  {
    prop: "departmentNumber",
    label: "部门编码"
  },
  {
    prop: "orderNum",
    label: "排序"
  },
  {
    prop: "status",
    label: "状态",
    tag: true,
    enum: statusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "createDate",
    label: "创建时间"
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

/** 初始化加载部门树形数据 */
onMounted(async () => {
  var dptList = await getDepartmentTree();
  if (dptList.data) {
    dptTree = [...dptList.data];
  }
});

/** 打开修改对话框 */
const openUpdateDialog = (param: DepartmentTreeResult) => {
  updateDialogVisible.value = true;
  Object.assign(updateParam, param);
};

/** 修改部门信息 */
const updateDepartment = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editDepartmentInfo(updateParam);
      insertDialogVisible.value = false;
      ElMessage.success("新增");
      await proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};

/** 修改部门状态 */
const updateDepartmentStatus = async (param: DepartmentTreeResult, status: number) => {
  await editDepartmentStatus({ departmentId: param.departmentId, status: status });
  ElMessage.success("修改状态");
  await proTable.value?.getTableList();
};

/** 选择部门新增子部门 */
const openInsertDialog = (param: DepartmentTreeResult) => {
  insertDialogVisible.value = true;
  insertParam.parentDepartmentId = param.departmentId;
};

/** 新增部门 */
const insertDepartment = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await createDepartment(insertParam);

      insertDialogVisible.value = false;
      ElMessage.success("新增");
      await proTable.value?.getTableList();
    } else {
      ElMessage.error("请填入必填数据");
    }
  });
};
</script>
